package com.example.da42;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.da20.TestConfig;
import jakarta.annotation.Resource;
import org.apache.poi.xwpf.usermodel.*;
import org.example.Easy2LearnApplication;
import org.example.domain.Question;
import org.example.excel.DataDAO;
import org.example.mapper.QuestionMapper;
import org.junit.jupiter.api.Test;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.*;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

@SpringBootTest(classes = {Easy2LearnApplication.class, TestConfig.class})
public class GetFromTxt {

    @Resource
    private QuestionMapper questionMapper;

    @Resource
    private DataDAO<Question> questionDataDAO;

    @Test
    public void test2(){
        List<Question> questionList = questionMapper.selectList(new LambdaQueryWrapper<Question>());
        setToWord(questionList);
    }

    /**
     * 将questions写入word
     * @param setQuestionList
     */
    private void setToWord(List<Question> setQuestionList) {
        String templatePath = "template.docx";
        String wordPath = "word.docx";
        try {
            File file = new File(templatePath);
            if (!file.exists()) {
                throw new RuntimeException("找不到模板文件");
            }
            InputStream is = Files.newInputStream(Paths.get(templatePath));
            XWPFDocument document = new XWPFDocument(is);

            //设置考卷信息
            List<XWPFParagraph> paragraphs = document.getParagraphs();
            XWPFParagraph paragraph = paragraphs.get(1);
            paragraph.getRuns().get(0).setBold(true);

            XWPFTable table = document.createTable(1, 2);
            table.setWidth("100%");
            // Set column widths (each column 50%)
            CTTblLayoutType tblLayout = table.getCTTbl().getTblPr().addNewTblLayout();
            tblLayout.setType(STTblLayoutType.FIXED);
            setTableBorders(table);

            for (int col = 0; col < 2; col++) {
                CTTblGridCol tblCol = table.getCTTbl().addNewTblGrid().addNewGridCol();
                tblCol.setW(BigInteger.valueOf(5000)); // Adjust the width as necessary
            }

            //插入第一道题目
            Question question0 = setQuestionList.get(0);
            XWPFTableCell cell0 = table.getRow(0).getCell(0);
            cell0.setText("1." +question0.getQuestion());
            mergeCellsHorizontally(table,0,0,1);
            int rowNum = 1;
            rowNum = setInnerQuestion(question0, table, rowNum);
            table.createRow();
            rowNum++;
            int questionNum = 2;

            //插入后面的题目
            for (int i = 1; i < setQuestionList.size(); i++) {
                Question question = setQuestionList.get(i);
                XWPFTableRow row = table.createRow();
                rowNum++;
                row.getCell(0).setText(questionNum + "." + question.getQuestion());
                mergeCellsHorizontally(table,rowNum-1,0,1);
                questionNum++;
                rowNum = setInnerQuestion( question, table, rowNum);
                table.createRow();
                rowNum++;
            }

            //设置答案
            setAnswer(document,setQuestionList);
            //Save the document
            FileOutputStream outputStream1 = new FileOutputStream(wordPath);
            document.write(outputStream1);
            outputStream1.close();
            document.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 取消表格的边框
     * @param table
     */
    private void setTableBorders(XWPFTable table) {
        // 设置表格的边框为0，即隐藏所有边框
        CTTblBorders tblBorders = table.getCTTbl().getTblPr().addNewTblBorders();
        tblBorders.addNewBottom().setVal(STBorder.NONE);
        tblBorders.addNewTop().setVal(STBorder.NONE);
        tblBorders.addNewLeft().setVal(STBorder.NONE);
        tblBorders.addNewRight().setVal(STBorder.NONE);
        tblBorders.addNewInsideH().setVal(STBorder.NONE);
        tblBorders.addNewInsideV().setVal(STBorder.NONE);
    }

    private int setInnerQuestion( Question question, XWPFTable table, int rowNum) {
        //如果答案比较长，则答案表格变成4行
        if (question.getItem1().length()>12|| question.getItem2().length()>12|| question.getItem3().length()>12|| question.getItem4().length()>12
        ) {
            XWPFTableRow row1 = table.createRow();
            XWPFTableRow row2 = table.createRow();
            XWPFTableRow row3 = table.createRow();
            XWPFTableRow row4 = table.createRow();
            rowNum +=4;
            row1.getCell(0).setText("A."+ question.getItem1());
            row2.getCell(0).setText("B."+ question.getItem2());
            row3.getCell(0).setText("C."+ question.getItem3());
            row4.getCell(0).setText("D."+ question.getItem4());

            mergeCellsHorizontally(table, rowNum -1,0,1);
            mergeCellsHorizontally(table, rowNum -2,0,1);
            mergeCellsHorizontally(table, rowNum -3,0,1);
            mergeCellsHorizontally(table, rowNum -4,0,1);
        }
//                否则答案表格变成2行
        else {
            XWPFTableRow row1 = table.createRow();
            XWPFTableRow row2 = table.createRow();
            rowNum +=2;
            row1.getCell(0).setText("A."+ question.getItem1());
            row1.getCell(1).setText("B."+ question.getItem2());
            row2.getCell(0).setText("C."+ question.getItem3());
            row2.getCell(1).setText("D."+ question.getItem4());

        }
        return rowNum;
    }


    // 方法用于水平合并单元格
    public void mergeCellsHorizontally(XWPFTable table, int row, int fromCol, int toCol) {
        for (int colIndex = fromCol; colIndex <= toCol; colIndex++) {
            XWPFTableCell cell = table.getRow(row).getCell(colIndex);
            if ( colIndex == fromCol ) {
                // The first merged cell is set with RESTART merge value
                cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
            } else {
                // Cells which join (merge) the first one, are set with CONTINUE
                cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);
            }
        }
    }


    /**
     * 设置答案
     * @param document
     * @param setQuestionList
     */
    private void setAnswer(XWPFDocument document, List<Question> setQuestionList) {
        document.createParagraph().createRun().setText("\n");

        String text =  "----------------------------------------------------------后面的为答案----------------------------------------------------------";
        document.createParagraph().createRun().setText(text);

        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < setQuestionList.size(); i++) {
            Question question = setQuestionList.get(i);
            String answer = question.getAnswer();
            builder.append(i+1+"."+answer+"   ");
        }
        document.createParagraph().createRun().setText(builder.toString());
    }


    @Test
    public void test() {
        String url = "C:\\Users\\84206\\Desktop\\机型题库校对_25.04.21.txt";
        List<String> lines = new ArrayList<>();

        try (BufferedReader reader = new BufferedReader(
                new FileReader(url, StandardCharsets.UTF_8))) {
            String line;
            while ((line = reader.readLine()) != null) {
                lines.add(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        List<Question> questions = new ArrayList<>();
        for (int i = 0; i < lines.size(); i++) {
            String line = lines.get(i);
            //如果line是以数字加.开头，比如12.以下关于利用控制面调节报告时的注意事项，说法错误的是_____。答案：C
            //就是以12.开头，同时是以答案：C，答案：D，答案：A，答案：B结尾
            if (line.matches("^\\d+\\..*答案：[ABCD]$")) {
                Question question = new Question();
                String substring = line.substring(0, line.indexOf("答案"));
                String substring2 = substring.substring(substring.indexOf(".")+1);
                String trim = substring2.trim();
                question.setQuestion(trim);
                String substring1 = line.substring(line.indexOf("答案") + 3, line.indexOf("答案") + 4);
                question.setAnswer(substring1);
                i++;
                line = lines.get(i);
                if (line!=null&&line.startsWith("id：")) {
                    substring = line.substring(line.indexOf("id：")+3, line.indexOf("id：") + 9);
                    question.setId(Long.parseLong(substring));
                    i++;
                    line = lines.get(i);
                    if (line != null&&line.startsWith("A.")) {
                        question.setItem1(line.substring(line.indexOf("A.") + 2));
                        i++;
                        line = lines.get(i);
                        if (line != null&&line.startsWith("B.")) {
                            question.setItem2(line.substring(line.indexOf("B.") + 2));
                            i++;
                            line = lines.get(i);
                            if (line != null&&line.startsWith("C.")) {
                                question.setItem3(line.substring(line.indexOf("C.") + 2));
                                i++;
                                line = lines.get(i);
                                if (line != null&&line.startsWith("D.")) {
                                    question.setItem4(line.substring(line.indexOf("D.") + 2));
                                    questions.add(question);
                                }
                            }
                        }
                    }
                }
            }

        }
        questionMapper.insert(questions);
        EasyExcel.write("C:\\Users\\84206\\Desktop\\42.xlsx",Question.class).sheet().doWrite(questions);
    }

}
